<template>
  <div>
    <p>正在登录，请稍后，如未跳转<br><br>
      <a style="color: #1482f0" :href="qq">QQ登录请点击这里</a><br><br>
      <a style="color: #1482f0" :href="gitee">Gitee登录请点击这里</a>
    </p>
    <p>{{ html }}</p>
    <el-dialog :title="title" :visible.sync="centerDialogVisible" width="20%" center>
      <el-input
        placeholder="请输入账号"
        v-model="username"
        clearable>
      </el-input>
      <br><br>
      <el-input
        placeholder="请输入密码"
        v-model="password"
        show-password
        clearable>
      </el-input>

      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="userVf()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { oauthLogin, registerUser, bindingUser } from '@/api/user'
import { setToken, setExp, setTokenType, getTokenType } from '@/utils/auth'
export default {
  name: 'Oauth',
  data() {
    return {
      html: '',
      username: '',
      password: '',
      title: '',
      type: false,
      centerDialogVisible: false
    }
  },
  computed: {
    ...mapGetters([
      'qq',
      'gitee'
    ])
  },
  created() {
    const token = this.$route.query.token
    const type = this.$route.query.type
    oauthLogin({ tokenUid: token, type: type }).then(res => {
      if (res.data.data === 0){
        this.html = res.data.msg
        this.oauthbtn(res)
      } else {
        this.$confirm('该三方账号没有绑定系统账户，是否绑定或注册', '提示', {
          confirmButtonText: '绑定',
          cancelButtonText: '注册',
          type: 'warning',
          center: true
        }).then(() => {
          this.title = '账号绑定'
          this.centerDialogVisible = true
          this.type = false
        }).catch(() => {
          this.title = '账号注册'
          this.centerDialogVisible = true
          this.type = true
        });
      }
    }).catch(r => {
      this.html = r
    })
  },
  methods:{
    userVf(){
      const token = this.$route.query.token
      const type = this.$route.query.type
      if (!this.type) {
        bindingUser({tokenUid: token, type: type,username: this.username,password: this.password}).then( res => {
          this.html = res.data.msg
          this.oauthbtn(res)
        })
      } else {
        registerUser({tokenUid: token, type: type,username: this.username,password: this.password}).then( res => {
          this.html = res.data.msg
          this.oauthbtn(res)
        })
      }
    },
    oauthbtn(res){
      const { token, overdue, tokentype } = res.headers
      setToken(token)
      setExp(overdue)
      setTokenType(tokentype)
      window.location = '/'
    }
  }
}
</script>
